package com.webchat.ugc.event.publisher;


import com.webchat.ugc.event.MallChatGeneralEvent;
import com.webchat.ugc.event.enums.GeneralEventTypeEnum;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MallChatGeneralEventPublisher {

    private static MallChatGeneralEventPublisher instance;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @PostConstruct
    private void init() {
        instance = this;
    }

    /**
     * 发布事件
     *
     * @param eventType
     * @param eventData
     */
    public static <T> void publish(GeneralEventTypeEnum eventType, T eventData) {

        MallChatGeneralEvent<T> generalEvent = new MallChatGeneralEvent<>(MallChatGeneralEventPublisher.class,
                                                                          eventType,
                                                                          eventData);
        publish(generalEvent);
    }

    public static <T> void publish(MallChatGeneralEvent<T> generalEvent) {

        if (instance != null && instance.applicationEventPublisher != null) {
            // 发布通用事件
            instance.applicationEventPublisher.publishEvent(generalEvent);
        } else {
            throw new RuntimeException("MallChatGeneralEventPublisher not initialized");
        }
    }

}
